package com.emm.yixun.poss.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.emm.yixun.common.enums.ProcessTypeEnums;
import com.emm.yixun.common.utils.PasswordUtil;
import com.emm.yixun.poss.mapper.TmMerchantMapper;
import com.emm.yixun.poss.domain.ReProcdef;
import com.emm.yixun.poss.domain.TmBaseCodeType;
import com.emm.yixun.poss.domain.TmBaseCodeValue;
import com.emm.yixun.poss.domain.TmMerchant;
import com.emm.yixun.poss.domain.TmMerchantResources;
import com.emm.yixun.poss.domain.TmResources;
import com.emm.yixun.poss.domain.TmUser;
import com.emm.yixun.poss.domain.TrMearchantProcdef;
import com.emm.yixun.poss.domain.TrMerchantDataAuthority;
import com.emm.yixun.poss.service.IReProcdefService;
import com.emm.yixun.poss.service.ITmBaseCodeTypeService;
import com.emm.yixun.poss.service.ITmBaseCodeValueService;
import com.emm.yixun.poss.service.ITmMerchantResourcesService;
import com.emm.yixun.poss.service.ITmMerchantService;
import com.emm.yixun.poss.service.ITmResourcesService;
import com.emm.yixun.poss.service.ITmUserService;
import com.emm.yixun.poss.service.ITrMearchantProcdefService;
import com.emm.yixun.poss.service.ITrMerchantDataAuthorityService;
import com.emm.yixun.poss.vo.MerchantVo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;

/**
 *
 * TmMerchant 表数据服务层接口实现类
 *
 */
@Service
public class TmMerchantServiceImpl extends SuperServiceImpl<TmMerchantMapper, TmMerchant> implements ITmMerchantService {
	@Autowired
	private ITmResourcesService resourcesService;
	@Autowired
	private ITmMerchantResourcesService rerchantResourcesService;
	
	@Autowired
	private IReProcdefService reProcdefService;
	
	@Autowired
	private ITrMearchantProcdefService mearchantProcdefService;
	
	@Autowired
	private ITmBaseCodeTypeService baseCodeTypeService;
	
	@Autowired
	private ITmBaseCodeValueService baseCodeValueService;
	
	@Autowired
	private ITmUserService userService;
	
	@Autowired
	private ITrMerchantDataAuthorityService merchantDataAuthorityService;
	
	/**
	 *
	 *1.新增商户 
	 *2.商户模块权限初始化(电话、call客、认筹)
	 *3.商户资源(菜单按钮)初始化
	 *4.商户流程初始化(默认17个流程)
	 *5.业务参数初始化
	 *
	 */
	@Transactional(rollbackFor = RuntimeException.class)
	public boolean addMerchant(MerchantVo merchantVo)throws Exception{
		//1.保存商户
		Long merchantId=saveMerchant(merchantVo);
		//2.创建商户admin账号
		initAdminUser(merchantVo,merchantId);
		//3.商户资源(菜单按钮)初始化;数据权限初始化
		initMerchantResources(merchantVo,merchantId);
		initDataAuthority(merchantVo,merchantId);
		//4.商户流程初始化(默认17个流程)
		initMerchantProcdef(merchantVo,merchantId);
		//5.业务参数初始化
		initBaseCode(merchantVo,merchantId);
		return true;
	}
	
	private void initDataAuthority(MerchantVo merchantVo,Long merchantId){
		List<TrMerchantDataAuthority> list=new ArrayList<TrMerchantDataAuthority>();
		Map<String, Object> columnMap=new HashMap<String,Object>();
		columnMap.put("merchant_id","1");
		columnMap.put("del_flag","0");
		//查询第一个商户数据资源组装
		List<TrMerchantDataAuthority> queryList=merchantDataAuthorityService.selectByMap(columnMap);
		if(null==queryList || queryList.size()==0){
			throw new RuntimeException("初始化商户管理员账号错误");
		}
		for(TrMerchantDataAuthority mda : queryList){
			mda.setId(null);
			mda.setCreateTime(new Date());
			mda.setMerchantId(merchantId);
			mda.setUpdateTime(new Date());
			list.add(mda);
		}
		boolean addOk=merchantDataAuthorityService.insertBatch(list);
		if(!addOk){
			throw new RuntimeException("初始化商户管理员账号错误");
		}
	}
	
	private void initAdminUser(MerchantVo merchantVo,Long merchantId){
		TmUser query=new TmUser();
		query.setUserPhone(merchantVo.getContactTel());
		query.setMerchantId(merchantId);
		int count=userService.selectCount(query);
		if(count>0){
			throw new RuntimeException("手机号码已存在");
		}
		TmUser tmUser=new TmUser();
		tmUser.setMerchantId(merchantId);
		tmUser.setUserCode(UUID.randomUUID().toString());
		tmUser.setCreateTime(new Date());
		tmUser.setDelFlag("0");
		tmUser.setCreateUserId(merchantVo.getCreateUserId());
		tmUser.setIsAdmin("1");
		tmUser.setSkin("skin-0");
		tmUser.setUpdateTime(new Date());
		tmUser.setUserStatus("0");
		tmUser.setUserAccount(merchantVo.getContactTel());
		tmUser.setUserPhone(merchantVo.getContactTel());
		tmUser.setUserPassword(PasswordUtil.md5Hex("x1234567"));
		tmUser.setUserName("系统管理员");
		boolean addOk=userService.insert(tmUser);
		if(!addOk){
			throw new RuntimeException("初始化商户管理员账号错误");
		}
	}
	@Transactional(rollbackFor = RuntimeException.class)
	public void correctParameter(String merchantId,String key,String values,String sort)throws Exception{
		TmMerchant tmMerchant=selectById(Long.valueOf(merchantId));
		TmBaseCodeType bctDto = new TmBaseCodeType();
		bctDto.setCodeType("01");
		bctDto.setTypeName(key);
		bctDto.setTypeValue(key);
		bctDto.setSort(String.valueOf(sort));
		bctDto.setRemark("初始化");
		bctDto.setMerchantId(tmMerchant.getId());
		bctDto.setCreateUserId(tmMerchant.getCreateUserId());
		bctDto.setDelFlag("0");
		bctDto.setCreateTime(new Date());
		boolean bctAddOk=baseCodeTypeService.insert(bctDto);
		if(!bctAddOk){
			throw new RuntimeException("初始化商户业务参数错误");
		}
		
		List<TmBaseCodeValue> codeValueList=new ArrayList<TmBaseCodeValue>();
		String[] codeValueArr = values.split(",");
		for(int jj=0; jj<codeValueArr.length; jj++){
			String codeValue = codeValueArr[jj];
			TmBaseCodeValue bcvDto = new TmBaseCodeValue();
			bcvDto.setCreateTime(new Date());
			bcvDto.setTypeId(bctDto.getId());
			bcvDto.setCodeName(codeValue);
			bcvDto.setCodeValue(codeValue);
			bcvDto.setSort(String.valueOf(jj+1));
			bcvDto.setRemark("初始化");
			bcvDto.setMerchantId(tmMerchant.getId());
			bcvDto.setCreateUserId(tmMerchant.getCreateUserId());
			bcvDto.setDelFlag("0");
			codeValueList.add(bcvDto);
			
		}
		bctAddOk=baseCodeValueService.insertBatch(codeValueList);
		if(!bctAddOk){
			throw new RuntimeException("初始化商户业务参数错误");
		}
	}
	
	private void initBaseCode(MerchantVo merchantVo,Long merchantId){
		String[] codeTypeArr = { "获知途径", "客户性质", "置业动机", "关注重点", "需求楼层", "生活服务", "生活配套", "希望庭院具备功能", "家庭结构",
				"目前居住的物业类型", "首次接触方式", "证件类型", "车驾品牌", "乐于参加的活动类型", "兴趣爱好", "日常信息获知途径", "目前居住的户型结构", 
				"学历","从事行业","公司性质","联系方式","目前居住/办公的房子属性"};
		String[][] codeValueArrs = {
				{ "报广媒体", "网络", "电台广播", "户外广告", "楼宇广告", "杂志", "直投", "会员", "展厅推荐", "房交会", "朋友介绍", "全员营销", "外部推荐",
						"CALL客", "短信", "派单", "工地现场及围挡", "拓客", "中介" },
				{ "自然到访", "员工", "工抵", "全员营销", "外部推荐", "渠道客户", "老带新", "分销推荐" },
				{ "婚房", "改善", "投资", "自住", "养老", "度假" },
				{ "地理位置", "商业配套", "周边配套", "生态环境", "健康服务", "建筑风水", "户型设计", "教育机构" },
				{ "多层", "小高层", "高层", "1层", "2层", "3层", "4层", "5层", "6层" },
				{ "酒店式礼宾服务", "酒店式前台服务", "酒店式商务服务", "菜单式房屋清洁服务", "私人生活秘书", "送餐服务", "文化、体育活动", "专车接送服务", "房屋租赁管理服务",
						"电话及访客留言", "健康、教育课程服务", "24小时便利店", "银行", "医院", "学校", "地铁", "公交", "菜场", "超市", "健身房", "药店",
						"图书馆" },
				{ "银行", "医院", "学校", "地铁", "公交", "菜场", "超市", "健身房" },
				{ "游泳池", "SPA池", "水景池", "烧烤台", "凉亭" },
				{ "独居", "夫妻二人", "二代同堂", "三代同堂", "四代同堂" },
				{ "酒店式公寓", "高层公寓", "多层公寓", "平层官邸", "排屋", "别墅", "中式大宅" },
				{ "来电", "来访" },
				{ "身份证", "护照", "营业执照", "户口薄", "军官证", "临时身份证", "港澳台同胞来往通行证", "边民出入境通行证", "外国人永久居留证", "警官证", "士兵证" },
				{ "无车", "奔驰", "宝马", "保时捷", "雷克萨斯", "丰田", "本田", "大众", "雪佛兰", "英菲尼迪", "奥迪", "沃尔沃", "标致", "现代", "别克",
						"福特", "马自达" },
				{ "修身养生类", "知识学习类", "少儿教育类", "老年人关爱类", "互动交流类", "园区体验类", "奢侈品体验类" },
				{ "运动", "上网", "收藏", "音乐", "文学", "摄影", "棋牌", "舞蹈", "旅游", "字画", "阅读", "影视剧", "综艺娱乐", "汽车", "奢侈品",
						"科技", "金融理财", "美容", "养生", "茶艺", "宠物", "烹饪" },
				{ "报纸", "网络", "电台广播", "微信等社交软件", "电视", "短信", "DM单页", "朋友" },
				{ "一室一厅", "两室一厅", "三室一厅", "三室两厅", "两室两厅" },
				{ "大专", "本科", "硕士", "博士", "博士后" },
				{ "工业制造", "贸易", "农林牧渔", "采矿业", "建筑业","房地产业","金融业","交通运输仓储和邮政业","IT行业（信息传输、计算机服务和软件业）","酒店/餐饮业","租赁（和商务服务业）","教育","医疗卫生","文化和体育","旅游","公共管理（政府机关等）和社会组织","科学研究和技术服务","国际组织" },
				{ "私企", "央企", "国企", "混合所有制"},
				{ "电话", "短信", "邮件"},
				{ "安置房", "自建房", "租房","单位分房","07年前老商品房","07年后老商品房","近百年来房子"}
			};
		for(int ii=0; ii<codeTypeArr.length; ii++){
			String typeName = codeTypeArr[ii];
			//创建类型
			TmBaseCodeType bctDto = new TmBaseCodeType();
			bctDto.setCodeType("01");
			bctDto.setTypeName(typeName);
			bctDto.setTypeValue(typeName);
			bctDto.setSort(String.valueOf(ii+1));
			bctDto.setRemark("初始化");
			bctDto.setMerchantId(merchantId);
			bctDto.setCreateUserId(merchantVo.getCreateUserId());
			bctDto.setDelFlag("0");
			bctDto.setCreateTime(new Date());
			boolean bctAddOk=baseCodeTypeService.insert(bctDto);
			if(!bctAddOk){
				throw new RuntimeException("初始化商户业务参数错误");
			}
			List<TmBaseCodeValue> codeValueList=new ArrayList<TmBaseCodeValue>();
			String[] codeValueArr = codeValueArrs[ii];
			for(int jj=0; jj<codeValueArr.length; jj++){
				String codeValue = codeValueArr[jj];
				TmBaseCodeValue bcvDto = new TmBaseCodeValue();
				bcvDto.setCreateTime(new Date());
				bcvDto.setTypeId(bctDto.getId());
				bcvDto.setCodeName(codeValue);
				bcvDto.setCodeValue(codeValue);
				bcvDto.setSort(String.valueOf(jj+1));
				bcvDto.setRemark("初始化");
				bcvDto.setMerchantId(merchantId);
				bcvDto.setCreateUserId(merchantVo.getCreateUserId());
				bcvDto.setDelFlag("0");
				codeValueList.add(bcvDto);
				
			}
			bctAddOk=baseCodeValueService.insertBatch(codeValueList);
			if(!bctAddOk){
				throw new RuntimeException("初始化商户业务参数错误");
			}
		}
	}
	
	private void initMerchantProcdef(MerchantVo merchantVo,Long merchantId){
		List<TrMearchantProcdef> list=new ArrayList<TrMearchantProcdef>();
		for(ProcessTypeEnums processType : ProcessTypeEnums.values()){
			Map<String, Object> columnMap=new HashMap<String,Object>();
			columnMap.put("KEY_", processType.getNo());
			List<ReProcdef> queryList=reProcdefService.selectByMap(columnMap);
			if(null==queryList || queryList.size()==0)continue;
			ReProcdef reProcdef=queryList.get(0);
			TrMearchantProcdef mpd=new TrMearchantProcdef();
			mpd.setMerchantId(merchantId);
			mpd.setCreateUserId(merchantVo.getCreateUserId());
			mpd.setCreateTime(new Date());
			mpd.setUpdateTime(new Date());
			mpd.setDelFlag("0");
			mpd.setProcKey(reProcdef.getProcessKey());
			mpd.setProcdefId(reProcdef.getId());
			mpd.setProcName(reProcdef.getName());
			mpd.setProcType(processType.getNo());
			list.add(mpd);
		}
		boolean insertOk=mearchantProcdefService.insertBatch(list);
		if(!insertOk){
			throw new RuntimeException("商户流程初始化(默认17个流程)错误");
		}
	}
	
	private void initMerchantResources(MerchantVo merchantVo,Long merchantId)throws Exception{
		EntityWrapper<TmResources> entityWrapper=new EntityWrapper<TmResources>();
		List<TmResources> resourcesList=resourcesService.selectList(entityWrapper);
		List<TmMerchantResources> mrList=new ArrayList<TmMerchantResources>();
		for(TmResources resources : resourcesList){
			TmMerchantResources merchantResources=new TmMerchantResources();
			merchantResources.setCreateTime(new Date());
			merchantResources.setCreateUserId(merchantVo.getCreateUserId());
			merchantResources.setDelFlag("0");
			merchantResources.setMerchantId(merchantId);
			merchantResources.setUpdateTime(new Date());
			merchantResources.setUpdateUserId(merchantVo.getCreateUserId());
			merchantResources.setResourcesCode(resources.getResourcesCode());
			mrList.add(merchantResources);
		}
		boolean insertOk=rerchantResourcesService.insertBatch(mrList);
		if(!insertOk){
			throw new RuntimeException("商户资源(菜单按钮)初始化错误");
		}
	}
	
	private Long saveMerchant(MerchantVo merchantVo){
		//1.组装商户 信息 
		//2.商户权限初始化(电话、call客、认筹)
		Date now=new Date();
		TmMerchant merchant=new TmMerchant();
		BeanUtils.copyProperties(merchantVo, merchant);
		merchant.setCreateTime(now);
		merchant.setUpdateTime(now);
		merchant.setDelFlag("0");
		merchant.setMerchantCode(UUID.randomUUID().toString());
		JSONArray switctInfo=new JSONArray();
		//电话开关
		JSONObject phoneSwitct=new JSONObject();
		phoneSwitct.put("type", "1");
		if(null!=merchantVo.getPhoneSwitct() && merchantVo.getPhoneSwitct()){
			phoneSwitct.put("status", "1");
		}else{
			phoneSwitct.put("status", "0");
		}
		//认筹开关
		JSONObject depositSwitch=new JSONObject();
		depositSwitch.put("type", "2");
		if(null!=merchantVo.getDepositSwitch() && merchantVo.getDepositSwitch()){
			depositSwitch.put("status", "1");
		}else{
			depositSwitch.put("status", "0");
		}
		//call客开关
		JSONObject callkeSwitch=new JSONObject();
		callkeSwitch.put("type", "3");
		if(null!=merchantVo.getCallkeSwitch() && merchantVo.getCallkeSwitch()){
			callkeSwitch.put("status", "1");
		}else{
			callkeSwitch.put("status", "0");
		}
		//4: 渠道推送认筹、认购、签约消息开关
		
		//5: OA,推送OA流程数据开关
		switctInfo.add(phoneSwitct);
		switctInfo.add(depositSwitch);
		switctInfo.add(callkeSwitch);
		merchant.setPhoneInformation(switctInfo.toJSONString());
		this.insert(merchant);
		return merchant.getId();
	}


}